package com.lijian.service.impl;

import com.lijian.dao.BlogDao;
import com.lijian.exception.NotFoundException;
import com.lijian.pojo.Blog;
import com.lijian.pojo.Type;
import com.lijian.service.BlogService;
import com.lijian.service.TypeService;
import com.lijian.utils.MarkdownUtils;
import com.lijian.utils.MyBeanUtils;
import com.lijian.vo.BlogVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    BlogDao blogDao;

    @Override
    @Transactional
    public Blog findBlogById(Long id) {
        return blogDao.findById(id).get();
    }

    @Override
    @Transactional
    public Page<Blog> listBlog(Pageable pageable, BlogVO blog) {
        return blogDao.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> predicates = new ArrayList<>();
                if (StringUtils.isNotBlank(blog.getTitle())) {
                    predicates.add(builder.like(root.<String>get("title"), "%" + blog.getTitle() + "%"));
                }
                if (blog.getTypeId() != null) {
                    predicates.add(builder.equal(root.<Type>get("type").get("id"), blog.getTypeId()));
                }
                if (blog.isRecommend()) {
                    predicates.add(builder.equal(root.<Boolean>get("recommend"), blog.isRecommend()));
                }
                query.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        }, pageable);
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable) {
        return blogDao.findAll(pageable);
    }

    @Transactional
    @Override
    public Page<Blog> listBlog(String query, Pageable pageable) {
        return blogDao.findByQuery(query, pageable);
    }

    @Override
    @Transactional
    public Blog addBlog(Blog blog) {
        if (blog.getId() == null) {
            blog.setCreateTime(new Date());
            blog.setUpdateTime(new Date());
            blog.setViews(0);
        } else {
            blog.setUpdateTime(new Date());
        }
        return blogDao.save(blog);
    }

    @Override
    @Transactional
    public Blog updateBlog(Long id, Blog blog) {
        Blog dbBlog = blogDao.findById(id).get();
        if (dbBlog == null) {
            throw new NotFoundException("博客找不到了");
        }
        //MyBeanUtils.getNullPropertyNames过滤为空的字段
        BeanUtils.copyProperties(blog, dbBlog, MyBeanUtils.getNullPropertyNames(blog));
        dbBlog.setUpdateTime(new Date());
        return blogDao.save(dbBlog);
    }

    @Override
    @Transactional
    public void deleteBlog(Long id) {
        blogDao.deleteById(id);
    }

    @Transactional
    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        Pageable pageable = new PageRequest(0, size, sort);

        return blogDao.findTop(pageable);
    }

    @Transactional
    @Override
    public Blog findBlogAndMarkdownToHtml(Long id) {
        Blog blog = blogDao.findById(id).get();
        if (blog == null) {
            throw new NotFoundException("博客找不到了");
        }
        /**
         * new一个新的blog，把数据库的blog拷贝到新的blog中
         * 用新的blog操作转换
         * 此操作不影响数据库查出来的blog值
         */
        Blog b = new Blog();
        BeanUtils.copyProperties(blog, b);
        String content = b.getContent();
        String htmlContent = MarkdownUtils.markdownToHtmlExtensions(content);
        b.setContent(htmlContent);
        //更新浏览次数
        blogDao.updateViews(id);
        return b;
    }

    @Transactional
    @Override
    public Page<Blog> listBlog(Long tagId, Pageable pageable) {
        return blogDao.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                Join join = root.join("tags");
                return builder.equal(join.get("id"), tagId);
            }
        }, pageable);
    }

    @Transactional
    @Override
    public Map<String, List<Blog>> archiveBlog() {
        List<String> years = blogDao.findGroupYear();
        Map<String, List<Blog>> map = new HashMap<>();
        for (String year : years) {
            map.put(year, blogDao.findByYear(year));
        }
        return map;
    }

    @Override
    public Long countBlog() {
        return blogDao.count();
    }
}
